package com.math.aistudykbr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    /**
     * 用于配置Redis连接工厂，使用了Jedis连接池
     * @return
     */
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return  new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 设置序列化器
//        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 该序列化器自动处理类型元数据，无需手动配置 ObjectMapper
        // 此配置会在 JSON 中添加 @class 字段（如 {"@class":"com.example.Message", "content":"..."}），反序列化时可根据该字段还原对象。
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        ObjectMapper om = new ObjectMapper();
//        jackson2JsonRedisSerializer.setObjectMapper(om);

        redisTemplate.setKeySerializer(new StringRedisSerializer());    // key的序列化器
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);   // value的序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());   // hash key的序列化器
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer); // hash value的序列化器

        redisTemplate.afterPropertiesSet(); // 确保初始化完成

        return redisTemplate;
    }
}
